package it.antonioduca.citt;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.media.AudioManager;
import android.util.Log;

public class FlipListener implements SensorEventListener {

	private final String TAG = "Citt";
	private final float TOLERANCE = 20; // Degrees
	private final float FACE_DOWN_Y_TRESHOLD = 180 - TOLERANCE; // 180 = y face down
	private final float FACE_DOWN_Z_TRESHOLD = 0 + TOLERANCE; // 0 = y face down
	private final float FACE_UP_Y_Z_TRESHOLD = 0 + TOLERANCE; // 0 = y|z face up

	private AudioManager audioManager;
	private boolean faceup = false;
	private boolean done = false;
	
	public FlipListener(AudioManager am) {
		super();
		audioManager = am;
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if(!done) {
			if(!faceup && Math.abs(event.values[1])<FACE_UP_Y_Z_TRESHOLD && Math.abs(event.values[2])<FACE_UP_Y_Z_TRESHOLD) {
				Log.i(TAG, "FACE UP -> Activating Citt...");
				faceup=true;
			}
			if(faceup && Math.abs(event.values[1])>FACE_DOWN_Y_TRESHOLD && Math.abs(event.values[2])<FACE_DOWN_Z_TRESHOLD) {
				Log.i(TAG, "FACE DOWN -> Activating vibrate mode...");
		    	audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
		    	done = true;
			}
		}
	}

}
